<template>
  <div class="reply-container">
    <!-- 主贴内容 -->
    <div class="main-post">
      <div class="main-post-header">
        <h2>主贴内容</h2>
      </div>
      <div class="post-item">
        <div class="post-user-info">
          <img 
            class="user-avatar" 
            :src="mainPost.isAnonymous ? '/default-avatar.png' : (mainPost.user?.head || '/default-avatar.png')" 
            :alt="mainPost.isAnonymous ? '匿名用户' : (mainPost.user?.realName + '的头像')"
          />
          <div class="user-name">{{ mainPost.isAnonymous ? '匿名用户' : mainPost.user?.realname }}</div>
        </div>
        <div class="post-content">
          <div class="post-header">
            <h3 class="post-title">{{ mainPost.title }}</h3>
            <span class="post-label">{{ mainPost.label?.labelName }}</span>
          </div>
          <div 
            class="post-text" 
            v-html="mainPost.content"
            @click="e => {
              if (e.target.tagName === 'IMG') handleImageClick(e.target.src)
              if (e.target.tagName === 'VIDEO') handleVideoClick(e)
            }"
          ></div>
          <div class="post-meta">
            <div class="post-left">
              <span class="time">发布时间：{{ mainPost.publishTime }}</span>
              <span class="views">浏览 {{ mainPost.viewCount }}</span>
              <span class="replies">回复 {{ mainPost.replyCount }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 回复列表 -->
    <div class="reply-list">
      <div class="reply-header">
        <h2>全部回复</h2>
        <el-button type="primary" @click="handleCreateReply">发表回复</el-button>
      </div>
      
      <div v-if="replies.length > 0">
        <div v-for="reply in replies" :key="reply.id" class="reply-item">
          <div class="post-user-info">
            <img 
              class="user-avatar" 
              :src="reply.isAnonymous ? '/default-avatar.png' : (reply.user?.head || '/default-avatar.png')" 
              :alt="reply.isAnonymous ? '匿名用户' : (reply.user?.realName + '的头像')"
            />
            <div class="user-name">{{ reply.isAnonymous ? '匿名用户' : reply.user?.realname }}</div>
          </div>
          <div class="reply-content">
            <div 
              class="reply-text" 
              v-html="reply.content"
              @click="e => {
                if (e.target.tagName === 'IMG') handleImageClick(e.target.src)
                if (e.target.tagName === 'VIDEO') handleVideoClick(e)
              }"
            ></div>
            <div class="reply-meta">
              <div class="reply-left">
                <span class="time">回复时间：{{ formatTime(reply.publishTime) }}</span>
              </div>
              <div class="post-right" v-if="reply.userId === userId">
                <button class="action-btn edit" @click="handleEditReply(reply)"   v-if="(isAdmin || userId === reply.userId)">编辑</button>
                <!-- <button class="action-btn delete" @click="handleDeletePost(post.id)">删除</button> -->
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="empty-reply">
        <el-empty description="暂无回复" />
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 回复编辑器对话框 -->
    <el-dialog
      :title="editReplyData ? '修改回复' : '发表回复'"
      v-model="dialogVisible"
      width="70%"
    >
      <el-form :model="replyForm" ref="replyFormRef" :rules="rules">
        <el-form-item label="匿名发布" prop="isAnonymous">
          <el-radio-group v-model="replyForm.isAnonymous">
            <el-radio :label="1">匿名</el-radio>
            <el-radio :label="0">不匿名</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="回复内容" prop="content">
          <RichTextEditor 
            v-model="replyForm.content"
            :on-image-upload="handleMediaUpload"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitReply">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="showImageViewer"
      :url-list="[currentImage]"
      :initial-index="0"
      @close="showImageViewer = false"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { Edit, Delete } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from '../plugins/axios'
import RichTextEditor from '../components/RichTextEditor.vue'

const route = useRoute()
const postId = route.params.id
const userId = ref(localStorage.getItem('userId') ? Number(localStorage.getItem('userId')) : null)
const isAdmin = localStorage.getItem('isAdmin') === '1'
// 主贴数据
const mainPost = ref({})

// 回复列表数据
const replies = ref([])

// 分页信息
const pagination = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

const formatTime = (time) => {
  if (!time) return ''
  return time.split('.')[0]  // 用分割的方式去掉 .0
}

// 获取主贴数据
const fetchMainPost = async () => {
  try {
    const response = await axios.get(`/post/${postId}`)
    if (response.data.code === 1) {
      mainPost.value = response.data.data
    }
  } catch (error) {
    console.error('获取主贴失败:', error)
  }
}

// 获取回复列表
const fetchReplies = async () => {
  try {
    const response = await axios.post('/reply/queryByCondition', {
      postId,
      page: pagination.value.currentPage,
      rows: pagination.value.pageSize
    })
    
    if (response.data.code === 1) {
      console.log(response.data.total)
      replies.value = response.data.data
      pagination.value.total = response.data.total || 0
    }
  } catch (error) {
    console.error('获取回复列表失败:', error)
  }
}

// 回复表单数据
const dialogVisible = ref(false)
const editReplyData = ref(null)
const replyForm = ref({
  postId: postId,
  content: '',
  isAnonymous: 0
})

// 表单验证规则
const rules = {
  content: [{ required: true, message: '请输入回复内容', trigger: 'blur' }]
}

// 处理发表回复
const handleCreateReply = () => {
  editReplyData.value = null
  replyForm.value = {
    postId: postId,
    content: '',
    isAnonymous: 0
  }
  dialogVisible.value = true
}

// 处理编辑回复
const handleEditReply = (reply) => {
  editReplyData.value = reply
  replyForm.value = {
    id: reply.id,
    postId: postId,
    content: reply.content,
    isAnonymous: reply.isAnonymous
  }
  dialogVisible.value = true
}

// 处理删除回复
const handleDeleteReply = async (replyId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条回复吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.delete(`/reply/${replyId}`)
    if (response.data.code === 1) {
      ElMessage.success('删除成功')
      fetchReplies()
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除回复失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理提交回复
const handleSubmitReply = async () => {
  try {
    const url = editReplyData.value ? '/reply/update' : '/reply/save'
    const response = await axios.post(url, replyForm.value)
    
    if (response.data.code === 1) {
      ElMessage.success(editReplyData.value ? '修改成功' : '回复成功')
      dialogVisible.value = false
      fetchReplies()
      fetchMainPost()
    } else {
      ElMessage.error(response.data.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交回复失败:', error)
    ElMessage.error('操作失败')
  }
}

// 分页处理
const handlePageChange = (newPage) => {
  pagination.value.currentPage = newPage
  fetchReplies()
}

const handlePageSizeChange = (newSize) => {
  pagination.value.pageSize = newSize
  pagination.value.currentPage = 1
  fetchReplies()
}

// 图片预览相关
const showImageViewer = ref(false)
const currentImage = ref('')

const handleImageClick = (src) => {
  currentImage.value = src
  showImageViewer.value = true
}

// 视频播放控制
const handleVideoClick = (event) => {
  const video = event.target
  if (video.paused) {
    video.play()
  } else {
    video.pause()
  }
}

onMounted(() => {
  fetchMainPost()
  fetchReplies()
})
</script>

<style scoped>
.reply-container {
  padding: 2rem;
  margin-top: 60px;
}

.main-post {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

.main-post-header {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #eee;
  background-color: #f8f9fa;
  border-radius: 8px 8px 0 0;
}

.main-post-header h2 {
  margin: 0;
  color: #333;
  font-size: 1.2rem;
  font-weight: 600;
}

.post-item {
  padding: 1.5rem;
  border-bottom: none;  /* 移除原有的底部边框 */
  background: transparent;  /* 移除原有的背景色 */
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.reply-header h2 {
  margin: 0;
  color: #333;
}

.post-user-info {
  width: 100px;
  text-align: center;
  margin-right: 20px;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-bottom: 8px;
}

.user-name {
  font-size: 14px;
  color: #666;
}

.post-content,
.reply-content {
  flex: 1;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.post-title {
  margin: 0;
  font-size: 1.2rem;
  color: #172B4D;
}

.post-label {
  padding: 0.25rem 0.75rem;
  background-color: #EAE6FF;
  color: #403294;
  border-radius: 3px;
  font-size: 0.8rem;
}

.post-text,
.reply-text {
  color: #42526E;
  margin-bottom: 1rem;
  line-height: 1.5;
}

.post-text :deep(img),
.post-text :deep(video),
.reply-text :deep(img),
.reply-text :deep(video) {
  height: 160px;
  width: auto;
  object-fit: contain;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.post-text :deep(img):hover,
.post-text :deep(video):hover,
.reply-text :deep(img):hover,
.reply-text :deep(video):hover {
  transform: scale(1.05);
}

/* 确保图片和视频不会超出容器 */
.post-text,
.reply-text {
  max-width: 100%;
  overflow: hidden;
}

/* 全屏时恢复原始尺寸 */
.post-text :deep(img):fullscreen,
.post-text :deep(video):fullscreen,
.reply-text :deep(img):fullscreen,
.reply-text :deep(video):fullscreen {
  height: auto;
  width: auto;
  max-height: 100vh;
}

.post-meta,
.reply-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.post-left,
.reply-left {
  display: flex;
  gap: 20px;
  color: #666;
  font-size: 0.9rem;
}

.reply-right {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.action-btn {
    padding: 0.25rem 0.75rem;
    border: 1px solid #DFE1E6;
    background-color: white;
    border-radius: 3px;
    cursor: pointer;
    font-size: 0.9rem;
    transition: all 0.2s;
  }
  
  .action-btn.assign {
    background-color: #fff;
    color: #409EFF;
    border: 1px solid #409EFF;
  }
  
  .action-btn.assign:hover {
    background-color: #ecf5ff;
    color: #409EFF;
    border-color: #409EFF;
  }
  
  .action-btn.edit {
    color: #67C23A;
    border: 1px solid #67C23A;
  }
  
  .action-btn.edit:hover {
    background-color: #f0f9eb;
    border-color: #67C23A;
    color: #67C23A;
  }
  
  .action-btn.delete {
    color: #F56C6C;
    border: 1px solid #F56C6C;
  }
  
  .action-btn.delete:hover {
    background-color: #fef0f0;
    border-color: #F56C6C;
    color: #F56C6C;
  }
  
.reply-item {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;  /* 添加更明显的分割线 */
  background: #fff;
  margin-bottom: 1px;  /* 添加一点间距 */
}

.reply-item:last-child {
  border-bottom: none;  /* 最后一个回复不需要分割线 */
}

.reply-list {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;  /* 确保圆角效果正常显示 */
}

.empty-reply {
  padding: 40px 0;
  text-align: center;
  background: #fff;
  border-radius: 8px;
  color: #909399;
}
</style> 